import {
  Injectable,
  HttpException,
  BadRequestException,
  NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Not, Repository } from 'typeorm';
import { Favorite } from '../../entities/favorite.entity';
import { Video } from '../../entities/video.entity';
import { CreateFavoriteDto } from './dto/create-favorite.dto';
import { FavoriteVideo } from 'src/entities/favorite-videos.entity';
import { RecommendationService } from '../recommendation/recommendation.service';
import { UpdateFavoriteDto } from './dto/update-favorite.dto';
import { GetFavoriteVideosDto } from './dto/get-favorite-videos.dto';

@Injectable()
export class FavoriteService {
  constructor(
    @InjectRepository(Favorite)
    private favoriteRepository: Repository<Favorite>,
    @InjectRepository(FavoriteVideo)
    private favoriteVideoRepository: Repository<FavoriteVideo>,
    @InjectRepository(Video)
    private videoRepository: Repository<Video>,
    private readonly recommendationService: RecommendationService,
  ) {}

  // 创建收藏夹
  async createFavorite(userId: number, createFavoriteDto: CreateFavoriteDto) {
    const favorite = new Favorite();
    favorite.name = createFavoriteDto.name;
    favorite.description = createFavoriteDto.description;
    favorite.is_public = createFavoriteDto.is_public;
    favorite.user = { id: userId } as any;

    try {
      await this.favoriteRepository.save(favorite);
      return favorite;
    } catch (error) {
      throw new HttpException('创建收藏夹失败', 400);
    }
  }

  // 获取用户的收藏夹列表
  async getFavorites(userId: number) {
    return await this.favoriteRepository.find({
      where: {
        user: { id: userId },
        is_delete: 0,
      },
      order: {
        created_at: 'DESC',
      },
    });
  }

  // 收藏视频
  async addVideoToFavorite(
    userId: number,
    favoriteId: number,
    videoId: number,
  ) {
    // 检查收藏夹是否存在且属于该用户
    const favorite = await this.favoriteRepository.findOne({
      where: {
        id: favoriteId,
        user: { id: userId },
        is_delete: 0,
      },
    });

    if (!favorite) {
      throw new HttpException('收藏夹不存在', 400);
    }

    // 检查视频是否存在
    const video = await this.videoRepository.findOne({
      where: {
        video_id: videoId,
        is_delete: 0,
      },
    });

    if (!video) {
      throw new HttpException('视频不存在', 400);
    }

    // 检查是否已经收藏
    const existingFavorite = await this.favoriteVideoRepository.findOne({
      where: {
        favorite: { id: favoriteId },
        video: { video_id: videoId },
      },
    });

    if (existingFavorite) {
      throw new HttpException('该视频已在收藏夹中', 400);
    }

    // 创建收藏关系
    const favoriteVideo = new FavoriteVideo();
    favoriteVideo.favorite = favorite;
    favoriteVideo.video = video;

    try {
      await this.favoriteVideoRepository.save(favoriteVideo);
      // 更新收藏夹视频数量
      favorite.video_count += 1;
      await this.favoriteRepository.save(favorite);

      // 更新用户推荐缓存
      await this.recommendationService.invalidateRecommendationCache(userId);

      return { message: '收藏成功' };
    } catch (error) {
      throw new HttpException('收藏失败', 400);
    }
  }

  // 取消收藏视频
  async removeVideoFromFavorite(
    userId: number,
    favoriteId: number,
    videoId: number,
  ) {
    const favorite = await this.favoriteRepository.findOne({
      where: {
        id: favoriteId,
        user: { id: userId },
        is_delete: 0,
      },
    });

    if (!favorite) {
      throw new HttpException('收藏夹不存在', 400);
    }

    const result = await this.favoriteVideoRepository.delete({
      favorite: { id: favoriteId },
      video: { video_id: videoId },
    });

    if (result.affected > 0) {
      // 更新收藏夹视频数量
      favorite.video_count -= 1;
      await this.favoriteRepository.save(favorite);
      return { message: '取消收藏成功' };
    }

    throw new HttpException('取消收藏失败', 400);
  }

  // 获取收藏夹中的视频列表
  async getFavoriteVideos( userId: number,
    favoriteId: number,
    query: GetFavoriteVideosDto,) {
    // 设置默认分页参数
  const page = query.page || 1;
  const limit = query.limit || 10;
  const skip = (page - 1) * limit;
  
  // 查找收藏夹
  const favorite = await this.favoriteRepository.findOne({
    where: { id: favoriteId, user: { id: userId }, is_delete: 0 },
  });

  // 收藏夹不存在或不属于该用户
  if (!favorite) {
    throw new NotFoundException('收藏夹不存在或无权访问');
  }

   // 构建查询条件
  let queryBuilder = this.favoriteVideoRepository
  .createQueryBuilder('favorite_video')
  .leftJoinAndSelect('favorite_video.video', 'video')
  .leftJoinAndSelect('video.user', 'user')
  .leftJoinAndSelect('video.category', 'category')
  .where('favorite_video.favorite_id = :favoriteId', { favoriteId })
  .andWhere('video.is_delete = :isDelete', { isDelete: 0 })
  .andWhere('video.status = :status', { status: 'approved' });


  // 添加关键词搜索
  if (query.keyword) {
    queryBuilder = queryBuilder
      .andWhere('(video.title LIKE :keyword OR category.name LIKE :keyword)', 
        { keyword: `%${query.keyword}%` });
  }

  // 查询总数
  const total = await queryBuilder.getCount();

  // 查询分页数据
  const favoriteVideos = await queryBuilder
    .orderBy('favorite_video.created_at', 'DESC')
    .skip(skip)
    .take(limit)
    .getMany();

    return favoriteVideos.map((fv) => fv.video);
  }

  // 删除收藏夹
  async deleteFavorite(userId: number, favoriteId: number) {
    const favorite = await this.favoriteRepository.findOne({
      where: {
        id: favoriteId,
        user: { id: userId },
        is_delete: 0,
      },
    });

    if (!favorite) {
      throw new HttpException('收藏夹不存在', 400);
    }

    if (favorite.is_default) {
      throw new HttpException('默认收藏夹不能删除', 400);
    }

    favorite.is_delete = 1;
    await this.favoriteRepository.save(favorite);
    return { message: '删除成功' };
  }

  /**
   * 更新收藏夹信息
   * @param userId 用户ID
   * @param favoriteId 收藏夹ID
   * @param updateFavoriteDto 更新收藏夹DTO
   * @returns 更新结果
   */
  async updateFavorite(
    userId: number,
    favoriteId: number,
    updateFavoriteDto: UpdateFavoriteDto,
  ) {
    // 查找收藏夹
    const favorite = await this.favoriteRepository.findOne({
      where: { id: favoriteId, user: { id: userId }, is_delete: 0 },
    });

    // 收藏夹不存在或不属于该用户
    if (!favorite) {
      throw new NotFoundException('收藏夹不存在或无权访问');
    }

    // 更新收藏夹信息
    if (updateFavoriteDto.name !== undefined) {
      // 检查名称是否已存在
      const existingFavorite = await this.favoriteRepository.findOne({
        where: {
          name: updateFavoriteDto.name,
          user: { id: userId },
          is_delete: 0,
          id: Not(favoriteId), // 排除当前收藏夹
        },
      });

      if (existingFavorite) {
        throw new BadRequestException('收藏夹名称已存在');
      }

      favorite.name = updateFavoriteDto.name;
    }

    if (updateFavoriteDto.description !== undefined) {
      favorite.description = updateFavoriteDto.description;
    }

    // 保存更新
    await this.favoriteRepository.save(favorite);

    return {
      code: 200,
      message: '更新收藏夹成功',
      data: {
        id: favorite.id,
        name: favorite.name,
        description: favorite.description,
        created_at: favorite.created_at,
      },
    };
  }
}
